﻿using System;
using System.Collections.Generic;

namespace Flagwind.Externals.Redis.Commands
{
	public class GetCommand : RedisCommandBase
	{
		#region 构造方法

		public GetCommand() : base("Get")
		{
		}

		public GetCommand(IRedisService redis) : base(redis, "Get")
		{
		}

		#endregion

		#region 执行方法

		protected override object OnExecute(Services.CommandContext context)
		{
			if(context.Expression.Arguments.Length < 1)
				throw new Flagwind.Services.CommandException("Missing arguments.");

			var result = new List<object>(context.Expression.Arguments.Length);

			for(int i = 0; i < context.Expression.Arguments.Length; i++)
			{
				var entry = this.Redis.GetEntry(context.Expression.Arguments[i]);

				if(entry == null)
				{
					context.Output.WriteLine(Services.CommandOutletColor.Red, $"The '{context.Expression.Arguments[i]}' entry is not existed.");
				}
				else
				{
					result.Add(entry);

					var entryType = this.Redis.GetEntryType(context.Expression.Arguments[i]);
					context.Output.Write(Services.CommandOutletColor.DarkGray, $"[{entryType}] ");

					switch(entryType)
					{
						case RedisEntryType.String:
							context.Output.WriteLine(result[i]);
							break;
						case RedisEntryType.Dictionary:
							context.Output.WriteLine(Services.CommandOutletColor.DarkYellow, $"The '{context.Expression.Arguments[i]}' dictionary have {((IRedisDictionary)entry).Count} entries.");
							break;
						case RedisEntryType.List:
							context.Output.WriteLine(Services.CommandOutletColor.DarkYellow, $"The '{context.Expression.Arguments[i]}' list(queue) have {((IRedisQueue)entry).Count} entries.");
							break;
						case RedisEntryType.Set:
						case RedisEntryType.SortedSet:
							context.Output.WriteLine(Services.CommandOutletColor.DarkYellow, $"The '{context.Expression.Arguments[i]}' hashset have {((IRedisHashset)entry).Count} entries.");
							break;
						default:
							context.Output.WriteLine();
							break;
					}
				}
			}

			if(result.Count == 1)
				return result[0];
			else
				return result;
		}

		#endregion
	}
}